package com.trytech.mongoocrawler.client.transport.http.cookie;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * cookie管理器
 */
public class HttpCookiesManager {
    //cookie容器
    public final static ConcurrentHashMap<String,HttpCookiesHolder> cookiesContainer = new ConcurrentHashMap<String,HttpCookiesHolder>();

    public static HttpCookiesHolder getCookiesHolder(String sessionId, String path){
        HttpCookiesHolder holder = cookiesContainer.get(sessionId);
        return holder;
    }

    public static List<HttpCookie> getCookies(String sessionId, String path){
        HttpCookiesHolder holder = cookiesContainer.get(sessionId);
        List<HttpCookie> cookieList = holder.getCookie(path);
        return cookieList;
    }

    public static HttpCookie getCookies(String sessionId, String path, String name){
        HttpCookiesHolder holder = cookiesContainer.get(sessionId);
        HttpCookie cookie = holder.getCookie(path, name);
        return cookie;
    }
    public static void addCookie(String sessionId, String name,String value,String domain){
        addCookie(sessionId,name, value, "/", domain, null, false);
    }
    public static void addCookie(String sessionId, String name,String value,String path, String domain){
        addCookie(sessionId,name, value, path, domain, null, false);
    }

    public static void addCookie(String sessionId, String name, String value, String path, String domain, String expires, boolean isSecure){
        HttpCookiesHolder holder = cookiesContainer.get(sessionId);
        if(holder == null){
            holder = new HttpCookiesHolder();
            cookiesContainer.put(sessionId, holder);
            holder = cookiesContainer.get(sessionId);
        }
        holder.addOrReplace(name,value,path,domain,expires,isSecure);
    }

    public static void removeAll(String sessionId){
        cookiesContainer.remove(sessionId);
    }

    public static void removeAll(String sessionId, String path){
        HttpCookiesHolder holder = cookiesContainer.get(sessionId);
        holder.delete(path);
    }

    public static void remove(String sessionId, String path, String name){
        HttpCookiesHolder holder = cookiesContainer.get(sessionId);
        holder.delete(path, name);
    }
}
